package com.jhinwins.equipmenteb.equipmentebserver.auth;

import com.jhinwins.equipmenteb.equipmentebserver.dao.UserDao;
import com.jhinwins.equipmenteb.equipmentebserver.entity.UserBean;
import com.jhinwins.equipmenteb.equipmentebserver.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Optional;

//@WebFilter(filterName = "customFilter", urlPatterns = "/*")
class CustomFilter implements Filter {
    private UserDao userDao;

    public CustomFilter(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println(UserUtils.curUser);
        if (UserUtils.curUser == null) {
            servletResponse.getWriter().write("NO_AUTH");
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}

//@Configuration
public class AuthFilter {
    @Autowired
    private UserDao userDao;

    @Bean
    public FilterRegistrationBean filterRegist() {
        FilterRegistrationBean frBean = new FilterRegistrationBean();
        frBean.setFilter(new CustomFilter(userDao));
        frBean.addUrlPatterns("/**");
        return frBean;
    }
}